package timing.ukulele.form.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import timing.ukulele.form.persistent.EntityConfig;
import timing.ukulele.form.persistent.EntityConfigDraft;
import timing.ukulele.form.persistent.EntityFieldConfig;
import timing.ukulele.form.persistent.EntityFieldConfigDraft;
import timing.ukulele.common.ResponseResult;
import timing.ukulele.form.mapper.EntityConfigDraftMapper;
import timing.ukulele.persistent.service.BaseService;
import com.google.common.collect.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class EntityConfigDraftService extends BaseService<EntityConfigDraftMapper, EntityConfigDraft> {

    final EntityConfigService configService;
    final EntityFieldConfigService fieldConfigService;
    final EntityFieldConfigDraftService fieldConfigDraftService;

    public EntityConfigDraftService(EntityConfigService configService,
                                    EntityFieldConfigService fieldConfigService,
                                    EntityFieldConfigDraftService fieldConfigDraftService) {
        this.configService = configService;
        this.fieldConfigService = fieldConfigService;
        this.fieldConfigDraftService = fieldConfigDraftService;
    }

    public IPage<EntityConfigDraft> getPage(Long systemId, int current, int size) {
        Page<EntityConfigDraft> page = new Page<>(current, size);
        LambdaQueryWrapper<EntityConfigDraft> query = new LambdaQueryWrapper<>();
        query.eq(EntityConfigDraft::getSystemId, systemId);
        query.orderByDesc(EntityConfigDraft::getId);
        IPage<EntityConfigDraft> iPage = getBaseMapper().selectPage(page, query);
        return iPage;
    }

    public ResponseResult<EntityConfigDraft> saveData(EntityConfigDraft configDraft) {
        if (configDraft.getId() == null || configDraft.getId() == 0) {
            configDraft.setCode(IdWorker.getId());
            this.save(configDraft);
            return ResponseResult.success(configDraft);
        } else {
            EntityConfigDraft updateDraft = new EntityConfigDraft();
            updateDraft.setDescription(configDraft.getDescription());
            updateDraft.setId(configDraft.getId());
            this.updateById(updateDraft);
            return ResponseResult.success(configDraft);
        }
    }

    public ResponseResult<Boolean> copyConfigDraft(Long existConfigDraftId) {
        //先查找该配置
        EntityConfigDraft configDraft =
                this.lambdaQuery().eq(EntityConfigDraft::getId, existConfigDraftId).one();
        if (Objects.isNull(configDraft)) {
            return ResponseResult.error("被复制的配置不存在!");
        }
        List<EntityFieldConfigDraft> draftFields = fieldConfigDraftService.lambdaQuery()
                .eq(EntityFieldConfigDraft::getEntityConfigDraftId, existConfigDraftId)
                .list();
        configDraft.setId(null);
        this.save(configDraft);
        if (!CollectionUtils.isEmpty(draftFields)) {
            draftFields.forEach(item -> {
                item.setId(0l);
                item.setEntityConfigDraftId(configDraft.getId());
            });
        }
        fieldConfigDraftService.saveBatch(draftFields);
        return ResponseResult.success(true);
    }

    /**
     * 草稿到正式版本
     *
     * @param holidayConfigDraftId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<String> enable(Long holidayConfigDraftId) {
        //启动主表
        EntityConfigDraft holidayConfigDraft = this.getById(holidayConfigDraftId);
        if (holidayConfigDraft == null) {
            return ResponseResult.error("草稿不存在");
        }
        EntityConfig entityConfig = new EntityConfig();
        BeanUtils.copyProperties(holidayConfigDraft, entityConfig);
        entityConfig.setId(null);

        List<EntityConfig> historyList = this.configService.lambdaQuery().eq(EntityConfig::getCode
                , entityConfig.getCode()).orderByDesc(EntityConfig::getVersion).select(EntityConfig::getVersion).list();
        if (CollectionUtils.isEmpty(historyList)) {
            entityConfig.setVersion(1);
        } else {
            entityConfig.setVersion(historyList.get(0).getVersion() + 1);
        }
        configService.save(entityConfig);

        //启用详情表
        List<EntityFieldConfigDraft> draftList = fieldConfigDraftService.lambdaQuery()
                .eq(EntityFieldConfigDraft::getEntityConfigDraftId, holidayConfigDraftId).list();
        if (CollectionUtils.isEmpty(draftList)) {
            return ResponseResult.error("没有详情数据，不建议启用");
        }
        ArrayList<EntityFieldConfig> fieldList = Lists.newArrayList();
        for (EntityFieldConfigDraft configDraft : draftList) {
            EntityFieldConfig fieldConfig = new EntityFieldConfig();
            BeanUtils.copyProperties(configDraft, fieldConfig);
            fieldConfig.setId(null);
            fieldConfig.setEntityConfigId(entityConfig.getId());
            fieldList.add(fieldConfig);
        }
        fieldConfigService.saveBatch(fieldList);
        return ResponseResult.success("启用成功");
    }
}
